/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package converters;

import com.aptech.bluepumpkin.Event;
import com.aptech.bluepumpkin.beans.EventFacade;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Trong Nguyen
 */
@ManagedBean
@SessionScoped
public class WinnerConverter implements Converter, Serializable {

    @EJB
    private EventFacade eventFacade;

    public WinnerConverter() {
        super();
        System.out.println("----------WinnerConverter constructed------------------");

    }

    private void init() {
        if (null == eventFacade) {
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

            eventFacade = (EventFacade) session.getAttribute("eventFacade");
            if (null != eventFacade) {
                System.out.println("WinnerConverter---------- get eventFacade from session");
            } else {
                System.out.println("-------eventFacade ---- is null");

            }
        } else {
            System.out.println("WinnerConverter----------eventFacade is not nulll");
        }
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null) {
            return null;
        }
        if (null == eventFacade) {
            init();
        }
        List<Event> allActiveEvents = eventFacade.getAllActiveEventsWithPrizes();
        for (Event event1 : allActiveEvents) {
            if (event1.getTitle().equals(value)) {
                return event1;
            }
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (null == value) {
            return "";

        }
        if (value instanceof String) {
            return (String) value;
        }
        if (value instanceof Event) {
            return ((Event) value).getTitle();
        }
        return null;
    }
}
